package org.carshared.principal;

import java.util.ArrayList;
import java.util.Calendar;

import org.carshared.R;
import org.carshared.sqlite.DBAdapterDateTravel;
import org.carshared.sqlite.DBAdapterPassenger;
import org.carshared.sqlite.DBAdapterTravel;
import org.carshared.utils.DateTravelBeen;
import org.carshared.utils.PassengerBeen;
import org.carshared.utils.TravelBeen;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.Toast;

import com.google.gson.Gson;

public class CalendarActivity extends ActionBarActivity {
	protected static final int PICK_DATA_TRAVEL = 0;
	private CalendarView calendarView;
	private Calendar selectedDate;
	private String travel;
	private TravelBeen dataTravel;
	private String user;
	private ArrayList<PassengerBeen> listaPasajerosViaje;
	private DBAdapterTravel dbHelper;
	private DBAdapterPassenger dbHelperPassenger;
	private DBAdapterDateTravel dbHelperDateTravel;
	Gson gson;
	private PassengerBeen p;
	private DateTravelBeen travelDate;
	private PassengerBeen pSelected;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);

		selectedDate = Calendar.getInstance();
		calendarView = (CalendarView) findViewById(R.id.calendar_view);
		// calendarView.setWeekSeparatorLineColor(Color.RED);
		listaPasajerosViaje = new ArrayList<PassengerBeen>();
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		// Manejadores bbdd
		dbHelper = new DBAdapterTravel(this);
		dbHelperPassenger = new DBAdapterPassenger(this);
		dbHelperDateTravel = new DBAdapterDateTravel(this);
		p = new PassengerBeen();
		// Recogemos datos pasados
		Bundle bundle = getIntent().getExtras();
		gson = new Gson();
		travel = bundle.getString("dataTravel");
		user = bundle.getString("user");
		dataTravel = gson.fromJson(travel, TravelBeen.class);

		calendarView.setOnDateChangeListener(new OnDateChangeListener() {
			@Override
			public void onSelectedDayChange(CalendarView view, int year,
					int month, int dayOfMonth) {
				Toast.makeText(
						getApplicationContext(),
						"Selected date is " + (month + 1) + "-" + dayOfMonth
								+ "-" + year, Toast.LENGTH_SHORT).show();
				selectedDate.set(year, month, dayOfMonth);
				if ("owner".equals(user)) {
					listaPasajerosViaje = dbHelperPassenger
							.fetchAllPassenger(dataTravel.getOrigenDestino());

				} else {
					p = dbHelperPassenger.fetchPassenger(dataTravel
							.getOrigenDestino());
					if (listaPasajerosViaje.size() != 0) {
						listaPasajerosViaje.clear();
					}

					listaPasajerosViaje.add(p);

				}

				Intent i = new Intent(CalendarActivity.this,
						DetailTravelActivity.class);
				i.putExtra("listaPasajeros", gson.toJson(listaPasajerosViaje));
				i.putExtra("user", user);
				startActivityForResult(i, PICK_DATA_TRAVEL);

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		float acumulado;
		if (resultCode == RESULT_OK) {

			dataTravel.setRecorrido(data.getStringExtra("dataTravel"));

			if ("owner".equals(user)) {

				pSelected = gson.fromJson(data.getStringExtra("Pasajero"),
						PassengerBeen.class);
				p = pSelected;
			}

			// Si el usuario ha pagado un viaje y se le asigna otro, se cambia
			// su estado a NO pagado
			if (p.isPagado()) {
				p.setPagado(false);
			}

			travelDate = new DateTravelBeen(selectedDate,
					dataTravel.getOrigenDestino(), p.getNombrePasajero());

			// Precio total del trayecto entre ocupantes y conductor
			float importeTrayectoIndividualOcupantes = dataTravel
					.getPrecioTrayecto() / (dataTravel.getnPasajeros() + 1);

			acumulado = p.getAcumulado();
			String soloIda = getResources().getString(R.string.IdaVuelta);
			if (soloIda.equals(dataTravel.getRecorrido())) {

				p.setAcumulado(acumulado + importeTrayectoIndividualOcupantes);
				dataTravel.setAcumulado(dataTravel.getAcumulado()
						+ importeTrayectoIndividualOcupantes);
			} else {

				// Multiplico *2 porque es ida y vuelta (2 trayectos)
				p.setAcumulado(acumulado
						+ (importeTrayectoIndividualOcupantes * 2));
				dataTravel.setAcumulado(dataTravel.getAcumulado()
						+ (importeTrayectoIndividualOcupantes * 2));
			}

			if (dbHelperDateTravel.createDateTravelBeen(travelDate) == -1
					|| dbHelper.update(dataTravel) == -1
					|| dbHelperPassenger.updatePassenger(p) == -1) {

				Toast.makeText(getApplicationContext(),
						"ERROR, Registro no guardado..", Toast.LENGTH_LONG)
						.show();

			} else {
				Toast.makeText(getApplicationContext(), "Guardado..",
						Toast.LENGTH_SHORT).show();
			}

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		return super.onCreateOptionsMenu(menu);
	}

	//
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		default:
			Intent intent = new Intent(this, BaseActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		}

		return true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

}